/*
 * Copyright 2005-2013 finalist.cn. All rights reserved.
 * Support: http://www.finalist.cn
 * License: http://www.finalist.cn/license
 */
package com.finalist.interceptor;

import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.finalist.service.MemberService;
import com.finalist.util.WebUtils;

/**
 * Interceptor - 令牌
 * 
 * @author Finalist IT Group
 * @version 3.0
 */
public class TokenInterceptor extends HandlerInterceptorAdapter
{

    /** "令牌"属性名称 */
    private static final String TOKEN_ATTRIBUTE_NAME = "token";

    /** "令牌"Cookie名称 */
    private static final String TOKEN_COOKIE_NAME = "token";

    /** "令牌"参数名称 */
    private static final String TOKEN_PARAMETER_NAME = "token";

    /** 错误消息 */
    private static final String ERROR_MESSAGE = "Bad or missing token!";

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
    	
    	/*StringBuffer url = request.getRequestURL();
    	int aa = url.indexOf("login.jhtml");
    	int bb =  url.indexOf("/common/"); 
    	int cc = url.indexOf("/login/");
    	int dd = url.indexOf("logout.jhtml");
    	int ee = url.indexOf("/admin/");
    	int ff = url.indexOf("/miaoReserve/");
    	int gg = url.indexOf("/article/hits/");	
    	 Member member = memberService.getCurrent();
    	if (aa>0 || bb>0 || cc>0 || dd>0 || ee>0 || ff>0 || gg>0 || member!=null) {
    		if (member!=null){
    			if (member.getId()!=1) {
        			response.sendRedirect("/login.jhtml");
        		}
    		}
    		
    	} else {
    		response.sendRedirect("/login.jhtml");
    	}
    	*/
    	
    	StringBuffer url = request.getRequestURL();
    	int apiBossUrl = url.indexOf("/api/bossArea");
    	int apiAppUrl = url.indexOf("/api/app");
    	if (apiBossUrl >= 0 ) {
    		return true;
    	}
    	if (apiAppUrl >= 0 ) {
    		return true;
    	}
    	
        String token = WebUtils.getCookie(request, TOKEN_COOKIE_NAME);
        if (request.getMethod().equalsIgnoreCase("POST"))
        {
            String requestType = request.getHeader("X-Requested-With");
            if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest"))
            {
                if (token != null && token.equals(request.getHeader(TOKEN_PARAMETER_NAME)))
                {
                    return true;
                }
                else
                {
                    response.addHeader("tokenStatus", "accessDenied");
                }
            }
            else
            {
                if (token != null && token.equals(request.getParameter(TOKEN_PARAMETER_NAME)))
                {
                    return true;
                }
            }
            if (token == null)
            {
                token = UUID.randomUUID().toString();
                WebUtils.addCookie(request, response, TOKEN_COOKIE_NAME, token);
            }
            if (request.getRequestURI().contains("voucherNotify") || request.getRequestURI().contains("notify") || request.getRequestURI().contains("external"))
            {
                return true;
            }
            response.sendError(HttpServletResponse.SC_FORBIDDEN, ERROR_MESSAGE);
            return false;
        }
        else
        {
            if (token == null)
            {
                token = UUID.randomUUID().toString();
                WebUtils.addCookie(request, response, TOKEN_COOKIE_NAME, token);
            }
            request.setAttribute(TOKEN_ATTRIBUTE_NAME, token);
            return true;
        }
    }

}